package com.hdu.kdk_feign.executor;

import com.alibaba.fastjson.JSON;
import com.hdu.kdk_feign.paramHandler.TotalRequestParamInfo;
import com.hdu.kdk_feign.paramHandler.Param;
import com.hdu.kdk_feign.paramHandler.ParamHandlerComposite;
import com.hdu.kdk_feign.utils.HttpUtils;


import java.util.List;

public class HttpExecutor implements Executor {

    private final List<Param> PARAM_LIST;
    private final String URL;
    private final Class<?> CLAZZ;
    private final HTTP_METHOD HTTP_METHOD;


    public HttpExecutor(String URL, List<Param> paramList, Class<?> CLAZZ, HttpExecutor.HTTP_METHOD httpMethod) {
        this.URL = URL;
        this.PARAM_LIST = paramList;
        this.CLAZZ = CLAZZ;
        this.HTTP_METHOD = httpMethod;
    }

    @Override
    public Object execute() {
        TotalRequestParamInfo totalRequestParamInfo = new TotalRequestParamInfo();
        ParamHandlerComposite.handle(totalRequestParamInfo, PARAM_LIST);
        String jsonStr;
        switch (HTTP_METHOD) {
            case GET:
                jsonStr = HttpUtils.doGet(
                        URL,
                        totalRequestParamInfo.getQueryParams(),
                        totalRequestParamInfo.getPathVariables() != null
                                ? totalRequestParamInfo.getPathVariables().toArray()
                                : null
                );
                break;
            case POST:
                jsonStr = HttpUtils.doPost(
                        URL,
                        totalRequestParamInfo.getRequestBody(),
                        totalRequestParamInfo.getQueryParams(),
                        totalRequestParamInfo.getPathVariables()
                );
                break;
            default:
                throw new UnsupportedOperationException("Unsupported HTTP method");

        }
        return JSON.parseObject(jsonStr, CLAZZ);
    }

    @Override
    public List<Param> getParamList() {
        return PARAM_LIST;
    }


    public enum HTTP_METHOD {
        POST, GET
    }
}
